<?php
declare (strict_types = 1);

namespace app\admin\model;

use app\admin\model\Common;

class Admin extends Common
{
	
	/**
	 * 管理组
	 */
	public function groups()
	{
		return $this->belongsToMany(AuthGroup::class, 'auth_group_access','group_id','uid');
	}
	
	/**
	 * 登录验证
	 */
	public function login($data){
		$info = $this
			->where('username','=',$data['username'])
			->find();
		if(empty($info)){
			return [
				'status' => 2,
				'notice' => '该用户不存在！',
			];
		}
		$password = md5($data['password']);
		if($password != $info['password']){
			return [
				'status' => 2,
				'notice' => '密码错误！',
			];
		}
		if(1 != $info->getData('status')){
			return [
				'status' => 2,
				'notice' => '该用户已经被限制登录！',
			];
		}
		$info->login_ip = get_client_ip();
		$info->last_login_ip = get_client_ip();
		$info->login_time = time();
		$info->last_login_time = time();
		$info->login_times = $info->login_times+1;
		$info->save();
		return [
			'status' => 1,
			'notice' => '登录成功！',
			'value' => $info->toArray()
		];
	}
	
	/**
	 * 修改个人信息
	 */
	public function profile($data){
		if(empty($data['password'])){
			unset($data['password']);
		} else {
			$data['password'] = md5($data['password']);
		}
		$admin = session('administrator');
		$id = intval($admin['id']);
		$info = $this->find($id);
		$re = $info->save($data);
		if(!empty($re)){
			session('administrator',$info);
			return [
				'status' => 1,
				'notice' => '操作成功！',
			];
		} else {
			return [
				'status' => 2,
				'notice' => '操作失败！',
			];
		}
	}
	
	/**
	 * 修改保存数据
	 */
	public function savedata($data){
		if(!empty($data)){
			if(!empty($data['auth_group'])){
				$auth_group = $data['auth_group'];
				unset($data['auth_group']);
			} else {
				$auth_group = [];
				unset($data['auth_group']);
			}
			if(empty($data['password'])){
				unset($data['password']);
			} else {
				$data['password'] = md5($data['password']);
			}
			if(!empty($data['id'])){
				$admin = $this->find($data['id']);
				$id = $admin->save($data);
				$idarr = $admin->groups()->column('id');
				$admin->groups()->detach($idarr);
				$mm = $admin->groups()->saveAll($auth_group);
				if(!empty($id)){
					return [
						'status'=>1,
						'notice'=>'操作成功！',
					];
				} else {
					return [
						'status'=>2,
						'notice'=>'操作失败！',
					];
				}
			} else{
				if(empty($data['password'])){
					return [
						'status'=>2,
						'notice'=>'密码不能为空！',
					];
				}
				$id = $this->save($data);
				$admin = $this->find($this->id);
				$admin->groups()->saveAll($auth_group);
				if(!empty($id)){
					return [
						'status'=>1,
						'notice'=>'操作成功！',
					];
				} else {
					return [
						'status'=>2,
						'notice'=>'操作失败！',
					];
				}
			}
		} else {
			return [
				'status'=>2,
				'notice'=>'数据不能为空！',
			];
		}
	}
	
	/**
	 * 获取器
	 */
	public function getStatusAttr($value){
		$config = config('tables.admin.fields.status.options');
		return $config[$value];
	}
}
